package com.example.common.network;

import com.example.common.model.BaseResponse;
import com.example.common.utils.LogUtil;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableTransformer;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class RxHelper {
    
    public static <T> ObservableTransformer<BaseResponse<T>, T> handleResult() {
        return upstream -> upstream
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(response -> {
                    LogUtil.d("RxHelper", "Response: " + response.toString());
                    if (response.isSuccess()) {
                        if (response.getData() != null) {
                            return Observable.just(response.getData());
                        } else {
                            return Observable.error(new ApiException(response.getCode(), "数据为空"));
                        }
                    } else {
                        return Observable.error(new ApiException(response.getCode(), response.getMessage()));
                    }
                })
                .onErrorResumeNext(throwable -> {
                    LogUtil.e("RxHelper", "Error: " + throwable.getMessage(), throwable);
                    return Observable.error(ApiException.handleException(throwable));
                });
    }
    
    public static <T> ObservableTransformer<T, T> applySchedulers() {
        return upstream -> upstream
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
}